package com.gzhryc.shared_device.oem.code.member.services;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.oem.code.member.dao.MemberRechargeOrderLogDao;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberRechargeOrder;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberRechargeOrderLog;

import java.sql.SQLException;
import java.util.Date;

public class MemberRechargeOrderLogService {

    static Logger log = Logger.getLogger(MemberRechargeOrderLogService.class);

    public static MemberRechargeOrderLogService self(Date date) {
        return MultiDBTools.getService(MemberRechargeOrderLogService.class, date);
    }

    public static MemberRechargeOrderLogService self(String jdbcKey,Date date) {
        return MultiDBTools.getService(jdbcKey, MemberRechargeOrderLogService.class, date);
    }

    MemberRechargeOrderLogDao dao;

    public MemberRechargeOrderLogService(String jdbcKey,Date date) {
        dao = new MemberRechargeOrderLogDao(jdbcKey,date);
    }


    public MemberRechargeOrderLog getByTradeNo(String tradeNo){
        try {
            return dao.getById(tradeNo);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public boolean add(MemberRechargeOrder rechargeOrder, OrderLogContent orderLogContent){
        MemberRechargeOrderLog orderLog = new MemberRechargeOrderLog();
        orderLog.setTradeNo(rechargeOrder.getTradeNo());
        orderLog.setContent(JsonTools.toJson(orderLogContent));
        orderLog.setCreateDate(new Date());
        try {
            return dao.insert(orderLog) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean add(String tradeNo,OrderLogContent.LogItem logItem){
        MemberRechargeOrderLog orderLog = getByTradeNo(tradeNo);
        if(orderLog != null && JsonTools.isJsonStr(orderLog.getContent())){
            OrderLogContent logContent = JsonTools.fromJson(orderLog.getContent(),OrderLogContent.class);
            logContent.getItems().add(logItem);

            MemberRechargeOrderLog updateEntity = new MemberRechargeOrderLog();
            updateEntity.setTradeNo(tradeNo);
            updateEntity.setContent(JsonTools.toJson(logContent));
            try {
                return dao.updateNotNull(updateEntity) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
}
